import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        isLoggedIn: false, // 初始状态，用户未登录
        user: null
    },
    mutations: {
        setLoggedIn(state, status) {
            state.isLoggedIn = status; // 更新登录状态
        },
        setUser(state, user) {
            state.user = user;
        }
    },
    actions: {
        async login({ commit }, { username, password }) {
            try {
                const response = await axios.post('http://127.0.0.1:5001/login', {
                    username,
                    password
                });
                if (response.status === 200) {
                    commit('setLoggedIn', true); // 登录时调用
                    commit('setUser', { username });
                    return true; // 登录成功
                }
                return false; // 登录失败
            } catch (error) {
                console.error("Login error:", error);
                return false; // 登录失败
            }
        },
        logout({ commit }) {
            commit('setLoggedIn', false); // 登出时调用
            commit('setUser', null);
        }
    }
});